"""
    -------开启服务后:
    1. 访问127.0.0.1:7788/shuogg.html:
        页面将显示shuogg.html的内容;

    2. 访问127.0.0.1:7788:
        页面显示index.html的内容;

    3. 访问127.0.0.1:7788/safsdf.html:
        页面将404;
"""

import socket
from multiprocessing import Process
import re

# 有新的客户端进来就用这个函数建条进程为他服务
def handleClient(clientSocket):
    recvData = clientSocket.recv(2048)
    requestHeaderLines = recvData.splitlines()      # 客户端的请求报文
    for line in requestHeaderLines:
        print(line.decode("utf-8"))
    httpRequestMethodLine = requestHeaderLines[0].decode("utf-8")
    getFileName = re.match("[^/]+(/[^ ]*)", httpRequestMethodLine).group(1)  # "GET /xxx HTTP/1.1" 获取其中的xxx
    print("File name is --->%s"%getFileName)
    if getFileName == '/':
        getFileName = documentRoot + "/index.html" 
    else:
        getFileName = documentRoot + getFileName

    try:
        f = open(getFileName)
    except IOError as e:
        responseHeaderLines = "HTTP/1.1 404 not found\r\n"
        responseHeaderLines += "\r\n"
        responseBody = "====sorry ,file not found===="
    else:
        responseHeaderLines = "HTTP/1.1 200 OK\r\n"
        responseHeaderLines += "\r\n"
        responseBody = f.read()
    finally:
        response = responseHeaderLines + responseBody
        response = response.encode("utf-8")
        clientSocket.send(response)
        clientSocket.close()

def main():
    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serverSocket.bind(("", 7788))
    serverSocket.listen(10)
    while True:
        clientSocket, clientAddr = serverSocket.accept()
        clientProcess = Process(target = handleClient, args = (clientSocket,))
        clientProcess.start()
        clientSocket.close()

documentRoot = './html_sample'
if __name__ == "__main__":
    main()